package cn.yunbamboos.mybatis.mapping.methods.custom;

import cn.yunbamboos.mybatis.mapping.methods.BaseMethod;
import cn.yunbamboos.mybatis.metadata.TableInfo;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.defaults.RawSqlSource;
import org.apache.ibatis.session.Configuration;

import java.util.ArrayList;
import java.util.List;

public class CustomQueryMethod extends BaseMethod {

    private String sql;

    private Class<?> resultType;

    public CustomQueryMethod(String methodName, Configuration configuration, TableInfo tableInfo) {
        super(methodName, configuration, tableInfo, SqlCommandType.SELECT);
    }

    @Override
    protected MappedStatement.Builder getMappedStatementBuilder() {
        Class<?> mapperType = tableInfo.getMapperType();
        MappedStatement.Builder builder = super.getMappedStatementBuilder();

        List<ResultMap> resultMaps = new ArrayList<>();

        String id = resultType.getName() + DOT + "ResultMap";
        if (configuration.hasResultMap(id)) {
            resultMaps.add(configuration.getResultMap(id));
        } else {
            ResultMap inlineResultMap = new ResultMap.Builder(configuration, mapperType.getName() + "-Inline", resultType, new ArrayList<>(), true).build();
            resultMaps.add(inlineResultMap);
        }
        builder.resultMaps(resultMaps);
        return builder;
    }

    @Override
    protected SqlSource getSqlSource() {
        return new RawSqlSource(configuration, this.sql, this.tableInfo.getEntityType());
    }

    public void setSql(String sql) {
        this.sql = sql;
    }

    public void setResultType(Class<?> resultType) {
        this.resultType = resultType;
    }
}